/**
 * @filename:SupplierContractServiceImpl 2022-03-22 02:40:49
 * @project com/lwl/blue  V1.0
 * Copyright(c) 2018 <a href=mailto:lanwenliang@yidianlife.com>蓝文良</a> Co. Ltd.
 * All right reserved.
 */
package com.lwl.blue.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lwl.blue.commont.base.*;
import com.lwl.blue.commont.enums.ExcelTemplateEnum;
import com.lwl.blue.commont.utils.DateUtils;
import com.lwl.blue.commont.utils.EasyExcelUtils;
import com.lwl.blue.commont.utils.ExcelTemplateUtil;
import com.lwl.blue.dao.SupplierContractDao;
import com.lwl.blue.entity.*;
import com.lwl.blue.excel.contract.CreateSupplierContractDetailExport;
import com.lwl.blue.excel.contract.CreateSupplierContractExport;
import com.lwl.blue.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>自定义serviceImpl写在这里</p>
 *
 * <p>说明： 工厂合同服务实现层</P>
 *
 * @version: V1.0
 * @author: <a href=mailto:lanwenliang@yidianlife.com>蓝文良</a>
 */
@Service
public class SupplierContractServiceImpl extends ServiceImpl<SupplierContractDao, SupplierContract> implements SupplierContractService {
    @Resource
    SupplierContractDao supplierContractDao;
    @Resource
    SupplierContractDetailService supplierContractDetailService;
    @Resource
    CustomerService customerService;
    @Resource
    ContractService contractService;
    @Resource
    ContractDetailService contractDetailService;

    @Override
    public JsonResult<Page<SupplierContract>> pages(PageParam<SupplierContract> pageParam) {
        Page<SupplierContract> page = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());
        return new JsonResult<Page<SupplierContract>>().success(supplierContractDao.pages(page, pageParam.getParam()));
    }


    @Override
    public void createSupplierContract(HttpServletResponse response, Integer id) {
        SupplierContract supplierContract = supplierContractDao.selectOne(new QueryWrapper<SupplierContract>().lambda().eq(SupplierContract::getId, id));
        CreateSupplierContractExport createSupplierContractExport = new CreateSupplierContractExport();
        List<SupplierContractDetail> detailList = supplierContractDetailService.list(new QueryWrapper<SupplierContractDetail>()
                .lambda()
                .eq(SupplierContractDetail::getSupplierContractId, id)
                .eq(SupplierContractDetail::getIsDelete, 0));
        if (detailList.isEmpty()) {
            throw new BizException(ErrorCode.CONTRACT_DETAIL_NOT_EXIST_ERROR.getCode(), ErrorCode.CONTRACT_DETAIL_NOT_EXIST_ERROR.getMsg());
        }
        BeanUtils.copyProperties(supplierContract, createSupplierContractExport);
        Customer customer = customerService.getById(supplierContract.getCustomerId());
        if(null==customer){
            throw new BizException(ErrorCode.CUSTOMER_NOT_ERROR.getCode(), ErrorCode.CUSTOMER_NOT_ERROR.getMsg());
        }
        createSupplierContractExport.setCustomerName(customer.getCustomerName());
        List<CreateSupplierContractDetailExport> list = new ArrayList<>();
        BigDecimal sumInnerBoxNumber = BigDecimal.ZERO;
        BigDecimal sumBoxNumber = BigDecimal.ZERO;
        BigDecimal sumTotalPrice = BigDecimal.ZERO;
        for (SupplierContractDetail d : detailList) {
            CreateSupplierContractDetailExport c = new CreateSupplierContractDetailExport();
            BeanUtils.copyProperties(d, c);
            list.add(c);
            c.setPhoto(EasyExcelUtils.getURL(d.getPhoto()));
            c.setDeliveryDate(DateUtils.formatLocalDate(LocalDate.now(), "yyyy-MM-dd"));
            if(Objects.nonNull(c.getInnerBoxNumber())&& Objects.nonNull(c.getSupplierPrice())){
                c.setTotalPrice(c.getInnerBoxNumber().multiply(c.getSupplierPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
                sumInnerBoxNumber = sumInnerBoxNumber.add(c.getInnerBoxNumber());
            }
            if(Objects.nonNull(c.getBoxNumber())){
                sumBoxNumber = sumBoxNumber.add(c.getBoxNumber());
            }
            if(Objects.nonNull(c.getTotalPrice())){
                sumTotalPrice = sumTotalPrice.add(c.getTotalPrice());
            }
        }
        createSupplierContractExport.setSumInnerBoxNumber(sumInnerBoxNumber);
        createSupplierContractExport.setSumBoxNumber(sumBoxNumber);
        createSupplierContractExport.setSumTotalPrice(sumTotalPrice);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String templateFileName = ExcelTemplateUtil.getExcelTemplatePath(ExcelTemplateEnum.CONTRACT_SUPPLIER);
        try {
            String rFileName = URLEncoder.encode("工厂合同", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + rFileName + ".xlsx");
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(templateFileName).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            // 如果有多个list 模板上必须有{前缀.} 这里的前缀就是 data1，然后多个list必须用 FillWrapper包裹
            excelWriter.fill(new FillWrapper("list", list), fillConfig, writeSheet);
            excelWriter.fill(createSupplierContractExport, writeSheet);
            // 别忘记关闭流
            excelWriter.finish();
        } catch (Exception exception) {
            exception.printStackTrace();
            throw new BizException(ErrorCode.SYS_EXCEPTION.getCode(), ErrorCode.SYS_EXCEPTION.getMsg());
        }

    }

    @Override
    public JsonResult createByContractId(Integer contractId, Integer supplierId) {
        if(0==supplierId){
            List<ContractDetail> list = contractDetailService.list(new QueryWrapper<ContractDetail>().lambda().eq(ContractDetail::getContractId, contractId));
           if(!CollectionUtils.isEmpty(list)){
               Set<Integer> supplierIds = list.stream().collect(Collectors.groupingBy(ContractDetail::getSupplierId)).keySet();
               for (Integer id:supplierIds) {
                   createByContractIdAndSupplierId(contractId,id);
               }
           }
        }else {
            createByContractIdAndSupplierId(contractId,supplierId);
        }
        return new JsonResult().success("生成工厂订单成功");
    }

    /**
     * 生成工厂订单
     * @param contractId
     * @param supplierId
     */
    private void createByContractIdAndSupplierId(Integer contractId, Integer supplierId){
        Contract contract = contractService.getById(contractId);
        LambdaQueryWrapper<ContractDetail> wrapper = new QueryWrapper<ContractDetail>().lambda()
                .eq(ContractDetail::getContractId, contractId)
                .eq(ContractDetail::getSupplierId, supplierId);
        List<ContractDetail> contractDetailList = contractDetailService.list(wrapper);
        SupplierContract add = new SupplierContract();
        BeanUtils.copyProperties(contract, add);
        add.setSupplierId(supplierId);
        add.setContractId(contractId);
        add.setContractNo(null);
        add.setContractName(null);
        BaseDataUtil.setInsetOrUpdateUser(add);
        this.save(add);
        if (!CollectionUtils.isEmpty(contractDetailList)) {
            List<SupplierContractDetail> addList = new ArrayList<>();
            contractDetailList.forEach(contractDetail -> {
                SupplierContractDetail addDetail = new SupplierContractDetail();
                BeanUtils.copyProperties(contractDetail, addDetail);
                addDetail.setSupplierContractId(add.getId());
                BaseDataUtil.setInsetOrUpdateUser(addDetail);
                addList.add(addDetail);
            });
            supplierContractDetailService.saveBatch(addList);
        }
    }
}
